<?php
namespace Home\Controller;

use Think\Controller;
use Think\Exception;
require(dirname(dirname(__FILE__))."/ORG/wx/wxBizMsgCrypt.class.php");
/**
 * @name 前端入口controller
 * @author perry
 * @version 1.0 2015-07-30
 */
class AuthController extends Controller {

	
	function _initialize(){
		$this->checkToken=C('third_check_token');
    $this->checkKey=C('third_check_key');
    $this->thirdAppid=C('third_app_id');
    $this->thirdAppsecret=C('third_app_secret');
    $this->sdk = new \Home\ORG\WeixinThirdSDK($this->thirdAppid,$this->thirdAppsecret);
	}

  //在自己的网站:中放置“微信公众号授权”的入口
	public function index() {
		//TODO https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=xxxx&pre_auth_code=xxxxx&redirect_uri=xxxx
    
    try {
      $preAuthCode=$this->sdk->pre_auth_code();
    } catch (\Exception $e) {
      dump('十分抱歉，站点维护中，请稍候再试.');
      $this->mydump($e);
      exit;
    }
    $retUrl=urlencode(C('auth_callback_url'));
    $url=sprintf("https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=%s&pre_auth_code=%s&redirect_uri=%s",$this->thirdAppid,$preAuthCode,$retUrl);
	  //以下代码全网发布前可以用，全网发布后不行了
    // header('location:' . $url);
    echo "<script>window.location.href='".$url."'</script>";
  }

  //授权后回调URI，得到授权码（authorization_code）和过期时间
  //授权流程完成后，授权页会自动跳转进入回调URI，并在URL参数中返回授权码和过期时间(redirect_url?auth_code=xxx&expires_in=600)
	public function call_back(){
    $auth_code=$_REQUEST['auth_code'];
    $expires_in=$_REQUEST['expires_in'];

    try {
      //公众号的接口调用凭据和授权信息
      $allPingju = $this->sdk -> getPingju($auth_code);
      //TODO p判断是否获得了有效凭据和接口信息
      $allPingju=$allPingju['authorization_info'];
      $m=D('Home/AuthorizationInfo');
      $m->addOne($allPingju);
      // dump($allPingju);
      //dump('您已成功授权。');
      echo('您已成功授权。');
    } catch (Exception $e) {
    }
  }

  public function mydump($msg){
    if($_REQUEST['debug']=='eosi'){
      dump($msg);
    }
  }
}